var dataSource = new Array();
//table的数据源
var table; //table对象
dataSource = [];

/*$(function () {
    var change = $("#js-export");
    change.attr("disabled", "disabled");
     change.attr("disabled", "disabled");
    change.css({'background': '#999', 'borderColor': '#999', 'color': '#fff'});
});*/
$(function () {

    $('#js-export').removeAttr('onclick');//去掉a标签中的onclick事件
    $("#js-export").css({'background': '#999', 'borderColor': '#999', 'color': '#fff'});
});
/*$(function () {
    $('#js-export').replaceWith(' <a href="javascript:return false;" class="btn btn-secondary radius size-S ml-10" id="d" onclick="derive(1)">导出</a></div>');
});*/

function reloadCouponTable() {
    $.ajax({
        contentType: 'application/json',
        /*root.orderInter.order_queryInovice*/
        url: root.orderInter.order_queryInovice,
        cache: false, //禁用缓存
        type: "POST",
        data: JSON.stringify({
            page_num: 1, //'页数',必传
            page_size: 50, //'数量',必传
            order_id: $("#order_id").val(), //订单号
            invoice_type: $("#invoice_type").val(), //发票类型
            invoice_status: $("#invoice_status").val(), //发票状态
            created_at_begin: $("#timemin").val(), //提交起始时间
            created_at_end: $("#timemax").val(), //提交终止时间
            customer_name: $("#customer_name").val(), //客户名称
            platform: crmCustomerIdOnearry, //订单来源平台
            warehouse_id: $("#shippingWarehouse option:selected").val(), //'仓库id'
            organization_name: $("#organization_name").val(), //'客户归属'
            companys_ids:sessionStorage.getItem("organizationWarehouse"),//公司对应的发货仓id
            warehouse_ids:sessionStorage.getItem("regions"),//仓库权限串
            belong_groupIds:sessionStorage.getItem("companys"),//销售归属权限串
            sales_manager_ids:sessionStorage.getItem("personnels"),//销售经理权限串
        }),
        success: function(data) {
            $('#js-export'). attr('onclick',"derive(1);");
            $('#js-export').removeAttr('style');
            sessionStorage.setItem("invoicestatus",'')
            console.log(data)
            $("#d").hide();
            invoiceList(data);
            var totalPage=0
            if(data.data!=null){
                totalPage = data.data.totalPage;
            }else {
                totalPage =0
            }

            $('.M-box3').pagination({
                pageCount: totalPage,
                jump: true,
                coping: true,
                prevContent: '上页',
                nextContent: '下页',
                callback: function(api) {
                    $.ajax({
                        contentType: 'application/json',
                        url: root.orderInter.order_queryInovice,
                        cache: false, //禁用缓存
                        type: "POST",
                        data: JSON.stringify({
                            page_num: api.getCurrent(), //'页数',必传
                            page_size: 50, //'数量',必传
                            order_id: $("#order_id").val(), //订单号
                            invoice_type: $("#invoice_type").val(), //发票类型
                            invoice_status: $("#invoice_status").val(), //发票状态
                            created_at_begin: $("#timemin").val(), //提交起始时间
                            created_at_end: $("#timemax").val(), //提交终止时间
                            customer_name: $("#customer_name").val(), //客户名称
                            platform: crmCustomerIdOnearry, //订单来源平台
                            warehouse_id: $("#shippingWarehouse option:selected").val(), //'仓库id'
                            organization_name: $("#organization_name").val(), //'客户归属'
                            companys_ids:sessionStorage.getItem("organizationWarehouse"),//公司对应的发货仓id
                            warehouse_ids:sessionStorage.getItem("regions"),//仓库权限串
                            belong_groupIds:sessionStorage.getItem("companys"),//销售归属权限串
                            sales_manager_ids:sessionStorage.getItem("personnels"),//销售经理权限串
                        }),
                        success: function(data) {
                            invoiceList(data);
                        }
                    });
                }
            });
        }
    });
}

function invoiceList(data) {
    if(dataSource.length>0){
        dataSource.splice(0, dataSource.length); //清空数组
    }
    if(data.data != null){
        $.each(data.data.result, function(i, field) {
            var rowData = new Array();
            rowData.push(field.order_id);
            rowData.push(field.platform);
            rowData.push(field.customer_name);
            rowData.push(field.organization_name);
            rowData.push(field.warehouse_id);
            rowData.push(field.order_status);
            rowData.push(field.commit_date);
            rowData.push(field.create_date);
            rowData.push(field.paid_amount);
            rowData.push(field.invoice_type);
            rowData.push(field.invoice_status);
            rowData.push(field.self_take_shop);
            rowData.push(field.invoice_role);
            rowData.push(field.operator_username);
            dataSource.push(rowData);
        });
    }

    initDataTable(dataSource);
    // console.log(dataSource)

    function initDataTable(dataSource) {
        var dttable = $('#datatable').dataTable(); // 初始化dataTable，清空上一个值
        dttable.fnClearTable(); //清空一下table
        dttable.fnDestroy(); //还原初始化了的datatable
        $("#datatable").DataTable({
            "autoWidth": false,
            "ordering": false,
            "searching": true,
            "paging": false,
            "retrieve": true,
            "destroy": true,
            "bAutoWidth": true,
            "bLengthChange": true,
            "aLengthMenu": [50],
            "oLanguage": {
                "sLengthMenu": "每页显示 _MENU_ 条记录",
                "sZeroRecords": "抱歉， 没有找到",
                "sInfo": "从 _START_ 到 _END_ /共 _TOTAL_ 条数据",
                "sInfoEmpty": "没有数据",
                "sInfoFiltered": "(从 _MAX_ 条数据中检索)",
                "oPaginate": {
                    "sFirst": "首页",
                    "sPrevious": "前一页",
                    "sNext": "后一页",
                    "sLast": "尾页"
                },
                "sZeroRecords": "没有检索到数据",
                "sProcessing": "<img src='./loading.gif' />"
            },
            data: dataSource,
            columnDefs: [{
                "visible": true,
                "targets": 0
            },
                {
                    "render": function(data, type, row, meta) {
                        if (row[1] == 10) {
                            var val = '普通平台';
                            return val;
                        } else if (row[1] == 20) {
                            var val = '签约平台';
                            return val;
                        } else if (row[1] == 30) {
                            var val = '第三方平台';
                            return val;
                        }else if (row[1] == 40) {
                            var val = '对接平台';
                            return val;
                        }
                    },
                    "targets": 1
                },
               /* {
                    "render": function(data, type, row, meta) {
                        var val = '';
                        if (row[1] == 10) {

                            if(row[10]==null || row[10]==""){
                                val=''
                            }else {
                                val=row[10]
                            }
                            console.log(row[10])
                        } else if (row[1] == 20) {
                            val=row[2]
                            console.log(row[2])
                        }
                        return val;
                    },
                    "targets": 2
                },*/
               /* {
                    "render": function(data, type, row, meta) {
                        var val = '';
                        return val;
                    },
                    "targets": 3
                },*/
                {
                    "render": function(data, type, row, meta) {
                        var warehouses=JSON.parse(sessionStorage.getItem("warehouses"))
                        var ss=""
                        $.each(warehouses.data,function(k,s){
                            if(row[4]==s.warehouseCode){
                                ss =s.warehouseName
                            }
                        })
                        if(row[4]==1 || row[4]==2 || row[4]==4|| row[4]==5|| row[4]==9|| row[4]==10|| row[4]==45|| row[4]==44|| row[4]==43|| row[4]==42|| row[4]==41|| row[4]==49|| row[4]==50){
                            var val =ss
                            return val;
                        }else {
                            var val = row[11];
                            return val;
                        }
                    },
                    "targets": 4
                },

                {
                    "render": function(data, type, row, meta) {
                        if(row[5] == 10 || row[5] == 9) {
                            var val = '待付款';
                            return val;
                        } else if(row[5] == 20) {
                            var val = '待审核';
                            return val;
                        } else if(row[5] == 30) {
                            var val = '待配货';
                            return val;
                        } else if (row[5] == 40) {
                            var val = '待出库';
                            return val;
                        } else if (row[5] == 50) {
                            var val = '已发';
                            return val;
                        } else if (row[5] == 60) {
                            var val = '待收货';
                            return val;
                        } else if (row[5] == 70) {
                            var val = '待结算';
                            return val;
                        } else if (row[5] == 80) {
                            var val = '交易成功';
                            return val;
                        } else if (row[5] == 90) {
                            var val = '交易完成';
                            return val;
                        } else if (row[5] == 100) {
                            var val = '订单取消';
                            return val;
                        } else if (row[5] == 110) {
                            var val = '交易关闭';
                            return val;
                        }
                    },
                    "targets": 5
                },
                {
                    "render": function(data, type, row, meta) {
                        if (row[6] == null) {
                            var val = '';
                            return val;
                        }
                        var date = row[6];
                        var split = date.split(" ");
                        var val = split[0] + '<br/>' + split[1];
                        return val;
                    },
                    "targets": 6
                },
                {
                    "render": function(data, type, row, meta) {
                        if (row[7] == null) {
                            var val = '';
                            return val;
                        }
                        var date = row[7];
                        var split = date.split(" ");
                        var val = split[0] + '<br/>' + split[1];
                        return val;
                    },
                    "targets": 7
                },
                {
                    "render": function(data, type, row, meta) {
                        var val = row[8];
                        return val;
                    },
                    "targets": 8
                },
                {
                    "render": function(data, type, row, meta) {
                        if (row[9] == 10) {
                            var val = '增值税';
                            return val;
                        } else if (row[9] == 20) {
                            var val = '普税';
                            return val;
                        } else if (row[9] == 30) {
                            var val = '未选择发票';
                            return val;
                        }
                    },
                    "targets": 9
                },
                {
                    "render": function(data, type, row, meta) {
                        if(row[10] == 20 || row[10] == 10) {
                            var val = '待开';
                            return val;
                        } else if(row[10] == 30) {
                            var val = '部分开';
                            return val;
                        } else if (row[10] == 40) {
                            var val = '已开';
                            return val;
                        } else if (row[10] == 50) {
                            var val = '已发';
                            return val;
                        }
                    },
                    "targets": 10
                },
                {
                    "render": function (data, type, row, meta) {
                        var val = ""
                        if (row[12] == 10) {
                            val = '客户'
                        }else {
                            val = '客服'
                        }
                        return val;
                    },
                    "targets": 11
                },
                {
                    "render": function (data, type, row, meta) {
                        var val = row[13]
                        if (val == undefined) {
                            val = ''
                        }
                        return val;
                    },
                    "targets": 12
                },
                {
                    "render": function (data, type, row, meta) {
                        if (row[10] == 20 || row[10] == 30 || row[10] == 10) {
                            var val = '<a class="powerButton 147"><span onclick="invoiceDetail(\'发票信息\', \'invoice-wait.html\',\''+row[0]+'\')">发票信息</span></a>';
                            return val;
                        } else if (row[10] == 40 || row[10] == 50) {
                            var val = '<a class="powerButton 147"><span onclick="invoiceDetail(\'发票信息\', \'invoice-open.html\',\''+row[0]+'\')">发票信息</span></a>';
                            return val;
                        }
                    },
                    "targets": 13
                }
            ],

        });
        //权限控制函数
        power()
    };
}

//查看发票信息
function invoiceDetail(title, url, row) {
    sessionStorage.setItem("orderId", row);
    var index = layer.open({
        type: 2,
        title: title,
        content: url
    });
    layer.full(index);
}


//导出按钮
/*$('#js-export').click(function(){
    window.location.href=root.orderInter.exportExcel;
});*/


//订单来源
var placeholder02html =[];//存放多选时的html
var placeholder02htmlinit =[];
var crmCustomerIdOnearry =[];//存放多选时的crmCustomerid
var spanhtml = '';
var crmCustomerIdOne='';
$(".ulbox").css('display','none');
/*点击 项目 显示下拉 选项,其中全选全不选，要做传值的处理*/
$(".dataval,.icon_arrow").on('click',function (e) {
    $(this).parent().children(".icon_arrow").toggleClass("icon_arrow_down");
    if($('.ulbox').css("display") == "none"){
        $('.ulbox').show();
        if($(".placeholder02").find(".all-radius")&&$(".placeholder02").find(".all-radius").html()=="全部"){
            $(".placeholder02").html("")

        }
    }else{
        $(".ulbox").hide();
        if ($(".placeholder02").html()==""){
            $(".placeholder02").html('<span class="all-radius">全部</span>')
        }
    }
    /*------------------8.24 如果已经有选择过的--------------------*/
    var initcustomerId =[];
    placeholder02htmlinit=[]
    $.each($(".lidata"),function (index,itm) {

        initcustomerId.push($(itm).attr('crmCustomerId'))
        placeholder02htmlinit.push($(itm).attr('crmCustomername'))
    })
    if(crmCustomerIdOnearry.length >0){
        function isArray(str){
            return Object.prototype.toString.call(str) == "[object Array]";
        }
        if(isArray(crmCustomerIdOnearry)){
            crmCustomerIdOnearry= [crmCustomerIdOnearry].join().split(',');
        }else{
            crmCustomerIdOnearry= [crmCustomerIdOnearry].join().split(',');
        }
        console.log(crmCustomerIdOnearry)
        $.each($(".lidata"),function (index,itm) {
            $.each(crmCustomerIdOnearry,function (i,item) {
                $.each(initcustomerId,function (j,ite) {
                    if(item == ite){
                        if($("itm").attr('crmcustomerid')==item){
                            $(".lidata").find('.evetyipt').prop('checked',true);
                        }
                    }
                })
            })
        })

    }
    e.stopPropagation();
});
var checkednum=0;
//当点击下拉数据时 回显在input里面
var htmlspan='';
$(".ulbox").on('click','input.evetyipt',function (e) {
    if($(".placeholder02").find(".all-radius")&&$(".placeholder02").find(".all-radius").html()=="全部"){
        $(".placeholder02").html("")

    }
    e.stopPropagation();
    if($(this).prop('checked')){
        $(this).prop('checked',true);//选中
        checkednum ++;
        spanhtml=$(this).next().html();
        placeholder02html.push(spanhtml);
        crmCustomerIdOne = $(this).parent().attr('crmCustomerId');
        crmCustomerIdOnearry.push(crmCustomerIdOne);
        $.each(placeholder02html,function(i,item){
            htmlspan = '<span>'+item+'</span>'
        })
        $(".placeholder02").append(htmlspan);
        if($(".ulbox").find('input.evetyipt').length == checkednum){
            $(".checkboxall").prev().prop('checked',true);
        }
        //全选反选时会用
        if (checkednum==0) {
            $(".checkboxall").prev().prop('checked',true);

        }
        //判断如果只选择了一个下拉选项 在input 里面应该展示全部的名称
        onenameadd()
    }else{
        checkednum --;
        $(this).prop('checked',false);
        var checkfalsehtml =  $(this).next().html();
        var tt =$(this).parent().attr('crmCustomerId');
        for (var i=0;i<crmCustomerIdOnearry.length;i++){
            if(crmCustomerIdOnearry[i] == tt){
                crmCustomerIdOnearry.splice(crmCustomerIdOnearry.indexOf(tt),1);
            }
        }
        var iptspandata = $('.placeholder02 span');//点击选中回显在span 里面的值
        $.each(iptspandata,function (i,item) {
            if($(item).html() == checkfalsehtml){
                $(item).html('');
                $(item).remove();
            }
        });
        placeholder02html.splice($(this).next().html(),1);
        if($(".ulbox").find('input.evetyipt').length != checkednum){
            $(".checkboxall").prev().prop('checked',false);
        }
        onename();
    }
});
//可点击空白处
$(document).click(function() {
    $(".ulbox").css('display','none');
    if ($(".placeholder02").html()==""){
        $(".placeholder02").html('<span class="all-radius">全部</span>')
    }
});
function onenameadd(){
    //判断如果只选择了一个下拉选项 在input 里面应该展示全部的名称
    if(crmCustomerIdOnearry.length == 1){
        $(".placeholder02 span").css('max-width','none');
        $(".placeholder02 span").attr('title',$(".placeholder02 span").html());
    }else{
        $(".placeholder02 span").css('max-width','48px');
    }
}
function onename(){
    //判断如果只选择了一个下拉选项 在input 里面应该展示全部的名称
    if(crmCustomerIdOnearry.length == 1){
        $(".placeholder02 span").css('max-width','none');
        $(".placeholder02 span").attr('title',$(".placeholder02 span").html());
    }
}

/*点击全选 联动 传值*/
var ulboxli = $(".ulbox").find('li');
$(".checkboxall").parent().on('click','input',function (e) {
    e.stopPropagation();
    if($(this).prop('checked')){//全选
        $(this).prop('checked',true);
        ulboxli.find('input').prop('checked',true);
        $(".placeholder02").html("")
        placeholder02html =placeholder02htmlinit;
        var htmlspan='';
        $.each(placeholder02html,function(i,item){
            htmlspan += '<span>'+item+'</span>'
        });
        var crmCustomerIds=$(this).attr('crmCustomerId')
        crmCustomerIdOnearry=crmCustomerIds.split(",")
        $(".placeholder02").append(htmlspan);
    }else{//全不选
        $(this).prop('checked',false);
        ulboxli.find('input').prop('checked',false);
        crmCustomerIdOnearry=[];
        placeholder02html=[];
        $(".placeholder02").html('');
    }
});
$(".ulbox").on('click','.checkboxall',function (e) {
    e.stopPropagation();
    if(  $(this).parent().find('input').prop('checked') == false){//全选
        $(this).parent().find('input').prop('checked',true);
        ulboxli.find('input').prop('checked',true);
        placeholder02html =placeholder02htmlinit;
        var htmlspan='';
        $.each(placeholder02html,function(i,item){
            htmlspan += '<span>'+item+'</span>'
        });
        $(".placeholder02").append(htmlspan);
    }else{//全不选
        $(this).parent().find('input').prop('checked',false);
        ulboxli.find('input').prop('checked',false);
        crmCustomerIdOnearry=[];
        placeholder02html=[];
        $(".placeholder02").html('');
    }
})

//弹框跳转
var invoicestatus= sessionStorage.getItem("invoicestatus")
var orderSource=sessionStorage.getItem("orderSource")//平台
if(invoicestatus==10){
    $('#invoice_status').val(invoicestatus)
    if(orderSource==40){
        crmCustomerIdOnearry=[]
        crmCustomerIdOnearry.push(40)
        placeholder02html.push("对接平台")
        var htmlspan=""
        $.each(placeholder02html,function(i,item){
            htmlspan += '<span>'+item+'</span>'
        });
        $(".placeholder02").html(htmlspan);
        $(".ulbox").find('input.evetyipt')[2].checked=true
    }else {
        var htmls="普通平台,签约平台"
        crmCustomerIdOnearry=[]
        crmCustomerIdOnearry=orderSource.split(",")
        placeholder02html=htmls.split(",")
        var htmlspan=""
        $.each(placeholder02html,function(i,item){
            htmlspan += '<span>'+item+'</span>'
        });
        $(".placeholder02").html(htmlspan);
        $(".ulbox").find('input.evetyipt')[0].checked=true
        $(".ulbox").find('input.evetyipt')[1].checked=true
    }

    reloadCouponTable()

}